package com.gexin.controller.commom;

import com.jfinal.log.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 京东万象快递信息查询接口
 * @author 徐佳俊
 */
@SuppressWarnings("deprecation")
public class ExpressApiController {
	static Log log = Log.getLog(ExpressApiController.class);
	//快递公司查询接口
	private static String company_url = "https://way.jd.com/showapi/company";
	//快递单查询接口
	private static String order_url = "https://way.jd.com/showapi/order_path";
	private static String appkey = "4f82cee9c69ac3b479c9c0d2e0e332e8";
	
	/**
	 * 快递单号实时查询接口
	 * @param com	快递公司英文简称
	 * @param no	快递单号
	 * @return
	 */
	public static String search(String com,String no){
		Map<String, String> data = new HashMap<String, String>();
		data.put("appkey", appkey);
		data.put("com", com);
		data.put("nu", no);
		String back = post(order_url, data);
		return back ;
	}
	
	/**
	 * 快递公司查询
	 * @param page	分页
	 * @param size	每页显示数据
	 * @return
	 */
	public static String company(int page,int size){
		Map<String, String> data = new HashMap<String, String>();
		data.put("appkey", appkey);
		data.put("maxSize", String.valueOf(size));
		data.put("page", String.valueOf(page));
		String back = post(company_url, data);
		return back;
	}
	
	@SuppressWarnings("resource")
	public static String post(String url,Map<String, String> param){
    	String body = null;
		HttpClient httpClient = new DefaultHttpClient();  
        try {
            // Post请求  
            HttpPost httppost = new HttpPost(url);
            // 设置参数  
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (String key : param.keySet()) {
            	params.add(new BasicNameValuePair(key, param.get(key)));
			}
            httppost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));   
            // 发送请求
            HttpResponse httpresponse = httpClient.execute(httppost);
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();  
            body = EntityUtils.toString(entity);
            if (entity != null) {  
                entity.consumeContent();  
            }  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return body;  
    }
}

